package sys.news.servlet;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import sys.news.pojo.News;
import sys.news.service.NewsSerice;
import sys.news.service.impl.NewsSericeImpl;
import sys.news.util.FileNameUtil;
import sys.news.vo.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/news.do")
public class NewsServlet extends HttpServlet {
private NewsSerice newsSerice = new NewsSericeImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost( req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //获取请求
            request.setCharacterEncoding("UTF-8");
            //设置响应
            response.setContentType("text/html;charset=utf-8");
            //控制请求路由
            String opr = request.getParameter("opr");
            switch (opr){
                case "add":{
                    add(request,response);
                    break;
                }
                case "del":{
                    del(request,response);
                    break;
                }
                case "gatAll":{
                    getAll(request,response);
                    break;
                }
                case "chechName":{
                    break;
                }
                case "getNewsByPage":{
                    getNewsByPage(request,response);
                }
                default:{
                    response.sendRedirect("/404.jsp");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            response.sendRedirect("/500.jsp");
        }

    }
    //增加新闻
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //servlet处理页面
        /*System.out.println("add新闻");
        News news = new News();
        news.setNauthor(request.getParameter("nauthor"));
        news.setNcontent(request.getParameter("ncontent"));
        news.setNcreateDate(request.getParameter("ncreatedate"));
        news.setNpicPath(request.getParameter("npicpath"));
        news.setNmodifyDate(request.getParameter("nmodifydate"));
        news.setNsummary(request.getParameter("nsummary"));
        news.setNtitle(request.getParameter("ntitle"));
        //响应
        HttpSession session = request.getSession();
        session.setAttribute("news_info",newsSerice.addNews(news));
        response.sendRedirect("admin/news_add.jsp");
*/
        System.out.println("add新闻");
        News news = new News();//新增的新闻
        //获取表单中的普通表单数据和文件数据
        //1、创建一个DiskFileItemFactory工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //2、创建一个文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解决上传文件名的中文乱码
        upload.setHeaderEncoding("UTF-8");
        //upload.setFileSizeMax(1024*1024*10); 10M
        //3、判断提交上来的数据是否是上传表单的数据
        if(!ServletFileUpload.isMultipartContent(request)){
            //按照传统方式获取数据
            return;
        }
        //4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
        try {
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem file : list){
                if(file.isFormField()){//普通表单数据
                    String name = file.getFieldName();//普通表单的name值
                    String value = file.getString("UTF-8");//普通表单的value值
                    switch(name){
                        case "ntid":{
                            news.setNtid(Integer.parseInt(value));
                            break;
                        }
                        case "ntitle":{
                            news.setNtitle(value);
                            break;
                        }
                        case "nauthor":{
                            news.setNauthor(value);
                            break;
                        }
                        case "nsummary":{
                            news.setNsummary(value);
                            break;
                        }
                        case "ncontent":{
                            news.setNcontent(value);
                            break;
                        }
                    }
                }else{//文件数据
                    try {
                        String savePath = request.getServletContext().getInitParameter("fileupload");//存储目录
                        //savePath = request.getServletContext().getRealPath("upload/");//tomcat/day14/web/upload
                        String oldName = file.getName();//原始文件名   1.png
                        String newName = FileNameUtil.makeFileName(oldName);  //asd123_1.png
                        String realSavePath = FileNameUtil.makePath(newName,savePath)+"/"+newName;// D:/newIO/3/4/asd123_1.png
                        file.write(new File(realSavePath));//上传
                        //解密路径
                        System.out.println("下载地址："+FileNameUtil.findFileSavePathByFileName(newName,savePath)+"/"+newName);
                        news.setNpicPath(newName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(newsSerice.addNews(news)));
        out.flush();
        out.close();
    }

    //删除新闻
    public void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       String param = request.getParameter("nid");
       int nid = Integer.valueOf(param);
       request.getSession().setAttribute("news_del",newsSerice.delNews(nid));
       response.sendRedirect("admin/news_del.jsp");
    }
    //查看所有新闻
    public void getAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.getSession().setAttribute("news_getAll",newsSerice.getAllNews());
        response.sendRedirect("admin/news_getAll.jsp");
    }
    public void getNewsByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //获取分数参数
        int currPageNo = request.getParameter("currPageNo")==null?1:Integer.parseInt(request.getParameter("currPageNo"));
        int pageSize = request.getParameter("pageSize")==null?15:Integer.parseInt(request.getParameter("pageSize"));
        Page<News> page = new Page<News>();
        page.setPageSize(pageSize);
        //获取参数条件
        News news = new News();
        int ntid  =  request.getParameter("ntid")==null?0:Integer.parseInt(request.getParameter("ntid"));
        news.setNtid(ntid);

        //响应
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(newsSerice.getNewsByPage(page,news)));
        out.flush();
        out.close();
    }
}
